<template>
  <view class="repair-container">
    <uni-section title="设备信息" type="line"></uni-section>

    <!-- 设备基本信息展示 -->
    <view class="device-info-card">
      <view class="info-item">
        <text class="info-label">设备名称：</text>
        <text class="info-value">{{ deviceInfo.equipmentName || deviceInfo.name || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">设备编号：</text>
        <text class="info-value">{{ deviceInfo.equipmentCode || deviceInfo.code || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">设备型号：</text>
        <text class="info-value">{{ deviceInfo.model || '未知' }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">设备状态：</text>
        <text class="info-value status" :class="statusClass">{{ statusText }}</text>
      </view>
    </view>

    <uni-section title="维修记录" type="line"></uni-section>

    <view class="form-container">
      <uni-forms ref="form" :model="formData" :rules="rules" label-width="180rpx">
        <!-- 维修类型 -->
        <!-- <uni-forms-item label="维修类型" name="repairType" required>
          <uni-data-select v-model="formData.repairType" :localdata="repairTypeOptions" placeholder="请选择维修类型" />
        </uni-forms-item> -->

        <!-- 故障描述 -->
        <uni-forms-item label="状态描述" name="statusDescription" required>
          <uni-easyinput v-model="formData.statusDescription" type="textarea" placeholder="请详细描述设备故障情况"
            :autoHeight="true" :maxlength="500" />
        </uni-forms-item>

        <!-- 维修方案 -->
        <uni-forms-item label="设备维修问题点" name="repairIssues" required>
          <uni-easyinput v-model="formData.repairIssues" type="textarea" placeholder="请描述维修问题点" :autoHeight="true"
            :maxlength="500" />
        </uni-forms-item>

        <!-- 维修人员 -->
        <uni-forms-item label="维修记录" name="repairRecords" required>
          <uni-easyinput v-model="formData.repairRecords" type="textarea" placeholder="请输入维修记录" :autoHeight="true"
            :maxlength="500" :clearable="true" />
        </uni-forms-item>

        <!-- 维修开始时间 -->
        <uni-forms-item label="预计完成时间" name="expectedCompletionTime" required>
          <uni-datetime-picker v-model="formData.expectedCompletionTime" value-format="yyyy-MM-dd HH:mm:ss" type="date"
            placeholder="请选择预计完成时间" />
        </uni-forms-item>

        <!-- 预计完成时间 -->
        <!-- <uni-forms-item label="预计完成时间" name="estimatedEndTime">
          <uni-datetime-picker v-model="formData.estimatedEndTime" type="datetime" placeholder="请选择预计完成时间" />
        </uni-forms-item> -->

        <!-- 状态描述处理情况 -->
        <uni-forms-item label="状态描述处理情况" name="completionStatus" required>
          <uni-data-checkbox v-model="formData.completionStatus" :localdata="statusHandlingOptions" />
        </uni-forms-item>

        <!-- 维修备注 -->
        <uni-forms-item label="备注" name="remark">
          <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入其他备注信息" :autoHeight="true"
            :maxlength="200" />
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn cancel" @click="handleCancel">取消</button>
      <button class="action-btn submit" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>

<script>
import { getEquipment, addRepairHistory, getNewestRepairHistory } from '@/api/equipment/main'

export default {
  data() {
    return {
      equipmentId: null,
      deviceInfo: {},
      formData: {
        equipmentId: '',
        repairType: '',
        statusDescription: '',
        repairIssues: '',
        repairRecords: '',
        expectedCompletionTime: '',
        estimatedEndTime: '',
        completionStatus: '',
        remark: ''
      },
      rules: {
        repairType: {
          rules: [
            { required: true, errorMessage: '请选择维修类型' }
          ]
        },
        statusDescription: {
          rules: [
            { required: true, errorMessage: '请输入状态描述' },
            { minLength: 1, maxLength: 500, errorMessage: '故障描述长度为1-500个字符' }
          ]
        },
        repairIssues: {
          rules: [
            { required: true, errorMessage: '请输入维修问题点' },
            { minLength: 1, maxLength: 500, errorMessage: '维修方案长度为1-500个字符' }
          ]
        },
        repairRecords: {
          rules: [
            { required: true, errorMessage: '请输入维修人员' },
            { minLength: 1, maxLength: 20, errorMessage: '维修人员姓名长度为1-20个字符' }
          ]
        },
        expectedCompletionTime: {
          rules: [
            { required: true, errorMessage: '请选择预计完成时间' }
          ]
        },
        completionStatus: {
          rules: [
            { required: true, errorMessage: '请选择状态描述处理情况' }
          ]
        }
      },
      repairTypeOptions: [
        { text: '预防性维修', value: '1' },
        { text: '故障维修', value: '2' },
        { text: '定期保养', value: '3' },
        { text: '紧急维修', value: '4' },
        { text: '升级改造', value: '5' }
      ],
      statusHandlingOptions: [
        { text: '已完成', value: '1' },
        { text: '未完成', value: '2' },
        // { text: '待处理', value: '3' },
        // { text: '无法处理', value: '4' },
        // { text: '需要更换', value: '5' }
      ]
    }
  },
  computed: {
    // 状态文本
    statusText() {
      const statusMap = {
        1: '在线',
        2: '离线',
        3: '告警',
        4: '待报废',
        5: '维修中',
        6: '已报废'
      }
      return statusMap[this.deviceInfo.status] || statusMap[String(this.deviceInfo.status)] || '未知'
    },
    // 状态样式类
    statusClass() {
      const classMap = {
        1: 'status-online',
        2: 'status-offline',
        3: 'status-alarm',
        4: 'status-pending',
        5: 'status-repairing',
        6: 'status-scrapped'
      }
      return classMap[this.deviceInfo.status] || classMap[String(this.deviceInfo.status)] || 'status-unknown'
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.equipmentId = options.id
      this.formData.equipmentId = options.id
      await this.fetchDeviceInfo()
    } else {
      uni.showToast({
        title: '缺少设备ID',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  methods: {
    // 获取设备信息
    async fetchDeviceInfo() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const res = await getEquipment(this.equipmentId)
        const data = res && res.data ? res.data : res

        this.deviceInfo = data

        // 如果设备状态为5（维修中），获取最新维修记录
        if (data.status === 5 || data.status === '5') {
          await this.fetchNewestRepairHistory()
        }

        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取设备信息失败:', error)
        uni.showToast({
          title: '获取设备信息失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    // 获取最新维修记录
    async fetchNewestRepairHistory() {
      try {
        const res = await getNewestRepairHistory(this.equipmentId)
        const data = res && res.data ? res.data : res

        if (data) {
          // 回填维修记录信息
          this.formData = {
            ...this.formData,
            repairType: data.repairType || '',
            statusDescription: data.statusDescription || '',
            repairIssues: data.repairIssues || '',
            repairRecords: data.repairRecords || '',
            expectedCompletionTime: data.expectedCompletionTime || '',
            estimatedEndTime: data.estimatedEndTime || '',
            completionStatus: data.completionStatus || '',
            remark: data.remark || ''
          }

          uni.showToast({
            title: '已加载最新维修记录',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('获取最新维修记录失败:', error)
        // 不显示错误提示，因为可能没有维修记录
      }
    },


    // 取消操作
    handleCancel() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消添加维修记录吗？未保存的数据将丢失。',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate().then(async (valid) => {
        if (valid) {
          try {
            uni.showLoading({
              title: '提交中...'
            })

            // 处理日期格式，将日期转换为 yyyy-MM-dd HH:mm:ss 格式
            const submitData = { ...this.formData }
            if (submitData.expectedCompletionTime) {
              // 如果日期格式是 yyyy-MM-dd，则添加 00:00:00
              if (submitData.expectedCompletionTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
                submitData.expectedCompletionTime = submitData.expectedCompletionTime + ' 00:00:00'
              }
            }

            // 调用添加维修记录的API
            const res = await addRepairHistory(submitData)

            uni.hideLoading()
            uni.showToast({
              title: '维修记录添加成功',
              icon: 'success'
            })

            // 延迟返回上一页
            setTimeout(() => {
              // 标记上一页需要刷新
              try { uni.setStorageSync('refresh_equipment_list', Date.now()) } catch (e) { }
              uni.navigateBack()
            }, 1500)

          } catch (error) {
            uni.hideLoading()
            console.error('添加维修记录失败:', error)
            uni.showToast({
              title: '添加维修记录失败',
              icon: 'none'
            })
          }
        }
      }).catch((errors) => {
        console.log('表单验证失败:', errors)
        uni.showToast({
          title: '请检查输入信息',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.repair-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.device-info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;

  &.status {
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    font-weight: 500;

    &.status-online {
      color: #34C759;
      background-color: #E8F5E8;
    }

    &.status-offline {
      color: #8E8E93;
      background-color: #F0F0F0;
    }

    &.status-alarm {
      color: #FF3B30;
      background-color: #FFE8E8;
    }

    &.status-pending {
      color: #FF9500;
      background-color: #FFF4E6;
    }

    &.status-repairing {
      color: #FF2D92;
      background-color: #FFE8F5;
    }

    &.status-scrapped {
      color: #5856D6;
      background-color: #E8E8FF;
    }

    &.status-unknown {
      color: #8E8E93;
      background-color: #F0F0F0;
    }
  }
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.cancel {
  background: #f0f0f0;
  color: #666;
}

.action-btn.submit {
  background: #007AFF;
  color: #fff;
}

.action-btn:active {
  opacity: 0.8;
}

// 表单项样式调整
.form-container :deep(.uni-forms-item) {
  margin-bottom: 8px !important;
  padding-bottom: 8px !important;
}

.form-container :deep(.uni-forms-item--border) {
  padding: 4px 0 !important;
}

.form-container :deep(.uni-forms-item__error) {
  padding-top: 2px !important;
}

:deep(.uni-forms-item__label) {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

:deep(.uni-easyinput__content) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-easyinput__content.is-focus) {
  border-color: #007AFF;
  background: #fff;
}

:deep(.uni-data-select) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-data-select.is-focus) {
  border-color: #007AFF;
  background: #fff;
}
</style>
